package com.example.demo.com.java8.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java8内置的四大核心函数式接口
 * Consumer<T> 消费型接口
 *   void accept(T t);
 * Supplier<T> 供给型接口
 *   T get();
 * Function<T,R> 函数型接口
 *  R apply(T t)
 * Predicate<T> 断言型接口
 *  boolean test(T t)
 * @author chengfei5
 * @date 2018/8/20
 */
public class LambdaTest3 {
    /**
     * 消费型接口
     */
    @Test
    public void test(){
        happy(1000,m-> System.out.println("买衣服花费"+m+"元"));
    }

    /**
     * 供给型接口
     */
    @Test
    public void test1(){
        System.out.println(getNumberList(10,()->{
            Random random = new Random();
            int i = random.nextInt(200);
            return i;
        }));
    }
    /**
     * 函数型接口
     */
    @Test
    public void test2(){
        System.out.println(stringHandle("agasgaesgsaeg",s -> s.substring(2,5)));

    }
    /**
     * 断言型接口
     */
    @Test
    public void test3(){
        List<String> list = Arrays.asList("hello","jingdongcaiyu","ok","lambda");
        System.out.println(filterStr(list,s -> s.length()>3));
    }

    /**
     * 消费型
     * @param money
     * @param consumer
     */
    public void happy(double money, Consumer<Double> consumer){
        consumer.accept(money);
    }
    /**
     * 过滤字符串集合
     * @param list
     * @param predicate
     * @return
     */
    public List<String> filterStr(List<String> list, Predicate<String> predicate){
        List<String> stringList = new ArrayList<>();
        for(String s:list){
            if(predicate.test(s)){
                stringList.add(s);
            }
        }
        return stringList;
    }
    /**
     * 字符串处理
     * @param str
     * @param function
     * @return
     */
    public String stringHandle(String str, Function<String,String> function){
        return function.apply(str);
    }
    /**
     * 产生一批整数，并放入集合中
     */
    public List<Integer> getNumberList(int num, Supplier<Integer> supplier){
        List<Integer> list = new ArrayList<>();
        for(int i = 0;i<num;i++){
            Integer n = supplier.get();
            list.add(n);
        }
        return list;
    }
}
